// api.js
import { SERVER_URL } from "@/config";

const apiClient = (() => {
  const base_url = `${SERVER_URL}/api`;

  const request = async (method, url, data = null, headers = {}) => {
    const options = {
      method,
      headers: {
        'Content-Type': headers['Content-Type'] || 'application/json',
      },
    };

    if (data && options.headers['Content-Type'] !== 'multipart/form-data') {
      options.body = JSON.stringify(data);
    } else if (data instanceof FormData) {
      // 不设置 Content-Type，浏览器会自动设置为 multipart/form-data 并添加边界
      options.body = data;
    }

    try {
      const response = await fetch(`${base_url}${url}`, options);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('An error occurred:', error);
      throw error;
    }
  };

  return {
    get: (url) => request('GET', url),
    post: (url, data, headers) => request('POST', url, data, headers),
    put: (url, data, headers) => request('PUT', url, data, headers),
    delete: (url) => request('DELETE', url),
  };
})();

export default apiClient;